import { defineStore } from 'pinia'
import { computed, reactive, ref, watch } from 'vue'
import type { Pagination } from '@/types/api'
import {
  createRequirement,
  getRequirementById,
  getRequirements,
  updateRequirement,
  updateRequirementStatus as apiUpdateRequirementStatus
} from '@/api/requirements'
import type { RequirementStatus } from '@/api/requirements'
import type {
  RequirementQueryParams,
  RequirementResponse,
  RequirementCreate,
  RequirementUpdate
} from '@/api/requirements'
import { getProjects, type ProjectResponse } from '@/api/project'
import type { User } from '@/types/user'
import { getProjectMembers } from '@/api/project'
import type { ProjectMember } from '@/types/project'
import { ElMessage } from 'element-plus'
import { useRequirementStates } from '@/composables/useRequirementStates'
import { useRequirementOptions } from '@/composables/useRequirementOptions'
import { useTagsStore } from '@/stores/tags'

type ViewMode = 'list' | 'kanban'
type EditorMode = 'create' | 'edit' | 'view'

interface RequirementPagination {
  page: number
  pageSize: number
  total: number
  pages: number
}

export interface RequirementFilters {
  search: string
  project_id?: string
  status?: string
  priority?: string
  requirement_type?: string
  source?: string
  assignee_id?: string
  reporter_id?: string
  has_version?: boolean
  created_start?: string
  created_end?: string
  sort_by?: string
  sort_order?: 'asc' | 'desc'
}

const DEFAULT_PAGE_SIZE = 20
const VIEW_PREFERENCE_KEY = 'pm.requirements.view-mode'

function extractProjects(response: { data?: any } | null | undefined): ProjectResponse[] {
  const payload = response?.data
  if (payload) {
    if (Array.isArray(payload.data)) {
      return payload.data as ProjectResponse[]
    }
    if (Array.isArray(payload.items)) {
      return payload.items as ProjectResponse[]
    }
    if (Array.isArray(payload)) {
      return payload as ProjectResponse[]
    }
  }
  return []
}


export const useRequirementsStore = defineStore('requirements', () => {
  const requirements = ref<RequirementResponse[]>([])
  const loading = ref(false)

  const pagination = reactive<RequirementPagination>({
    page: 1,
    pageSize: DEFAULT_PAGE_SIZE,
    total: 0,
    pages: 0
  })

  const storedViewMode = localStorage.getItem(VIEW_PREFERENCE_KEY) as ViewMode | null
  const initialViewMode: ViewMode = storedViewMode === 'kanban' ? 'kanban' : 'list'

  const viewMode = ref<ViewMode>(initialViewMode)

  watch(
    viewMode,
    mode => {
      localStorage.setItem(VIEW_PREFERENCE_KEY, mode)
    },
    { immediate: true }
  )

  const filters = reactive<RequirementFilters>({
    search: '',
    sort_by: undefined,
    sort_order: undefined
  })

  const selectedIds = ref<string[]>([])
  const activeRequirementId = ref<string | null>(null)
  const activeRequirement = ref<RequirementResponse | null>(null)

  const editorVisible = ref(false)
  const editorMode = ref<EditorMode>('create')
  const editorLoading = ref(false)
  const editorDefaultProjectId = ref<string | null>(null)

  const detailVisible = ref(false)
  const detailLoading = ref(false)

  const projects = ref<ProjectResponse[]>([])
  const users = ref<User[]>([])
  const { statusOptions, allStatusOptions, loadStates: loadRequirementStates } = useRequirementStates()
  const { 
    priorityOptions: formattedPriorityOptions, 
    formattedTypeOptions,
    formattedSourceOptions,
    loadOptions: loadRequirementOptions 
  } = useRequirementOptions()
  const tagsStore = useTagsStore()
  
  // 使用格式化后的优先级选项
  const priorityOptions = formattedPriorityOptions
  
  // 使用格式化后的类型选项
  const typeOptions = formattedTypeOptions
  
  // 使用格式化后的来源选项
  const sourceOptions = formattedSourceOptions

  const paginationMeta = ref<Pagination | null>(null)

  const currentQuery = computed<RequirementQueryParams>(() => {
    const query: RequirementQueryParams = {
      page: pagination.page,
      size: pagination.pageSize
    }

    if (filters.search) query.search = filters.search
    if (filters.project_id) query.project_id = filters.project_id
    if (filters.status) query.status = filters.status as any
    if (filters.priority) query.priority = filters.priority as any
    if (filters.requirement_type) query.requirement_type = filters.requirement_type as any
    if (filters.source) query.source = filters.source as any
    if (filters.assignee_id) query.assignee_id = filters.assignee_id
    if (filters.reporter_id) query.reporter_id = filters.reporter_id
    if (typeof filters.has_version === 'boolean') query.has_version = filters.has_version
    if (filters.created_start) query.created_at_start = filters.created_start
    if (filters.created_end) query.created_at_end = filters.created_end
    if (filters.sort_by) query.sort_by = filters.sort_by
    if (filters.sort_order) query.sort_order = filters.sort_order

    return query
  })

  const hasSelection = computed(() => selectedIds.value.length > 0)
  
  // 标签选项：从标签管理API获取，同时包含需求中已使用的标签
  const tagOptions = computed(() => {
    const tagSet = new Set<string>()
    // 添加系统标签（从标签管理模块获取）
    tagsStore.tags.forEach(tag => {
      if (tag.module_type === 'requirement' || !tag.module_type) {
        tagSet.add(tag.name)
      }
    })
    // 添加需求中已使用的标签（作为补充）
    requirements.value.forEach(req => {
      req.tags?.forEach(tag => tagSet.add(tag))
    })
    activeRequirement.value?.tags?.forEach(tag => tagSet.add(tag))
    return Array.from(tagSet)
  })

  // 基础数据加载缓存
  let bootstrapPromise: Promise<void> | null = null
  let lastBootstrapTime = 0
  const BOOTSTRAP_CACHE_TIME = 5 * 60 * 1000 // 5分钟缓存

  // 将项目成员转换为用户格式
  function convertProjectMembersToUsers(members: ProjectMember[]): User[] {
    return members.map(member => ({
      id: member.user_id,
      username: member.username || member.user_name || '',
      name: member.name || member.username || member.user_name || '',
      email: member.email || member.user_email || '',
      avatar: member.avatar,
      roles: member.roles || (member.role ? [member.role] : []),
      status: 'active' as const,
      is_verified: false,
      created_at: member.joined_at,
      updated_at: member.joined_at
    }))
  }

  // 根据项目ID获取用户列表（项目成员）
  async function loadUsersByProject(projectId?: string): Promise<User[]> {
    if (!projectId) {
      // 如果没有项目ID，返回空数组或系统用户（根据需求决定）
      // 这里返回空数组，让调用方决定是否使用系统用户
      return []
    }

    try {
      const response = await getProjectMembers(projectId)
      if (response.success && response.data) {
        // API返回的data可能是数组，也可能是包含members字段的对象
        let members: ProjectMember[] = []
        if (Array.isArray(response.data)) {
          // 如果data直接是数组
          members = response.data
        } else if (response.data && typeof response.data === 'object' && 'members' in response.data) {
          // 如果data是对象，包含members字段（实际后端返回格式）
          members = Array.isArray((response.data as any).members) ? (response.data as any).members : []
        }
        return convertProjectMembersToUsers(members)
      }
      return []
    } catch (error) {
      console.error('获取项目成员失败:', error)
      return []
    }
  }

  async function bootstrapOptions(forceRefresh = false) {
    // 如果不是强制刷新，且缓存有效，且正在加载，返回同一个 Promise
    if (!forceRefresh && bootstrapPromise) {
      return bootstrapPromise
    }

    // 如果不是强制刷新，且缓存有效，直接返回
    if (!forceRefresh && Date.now() - lastBootstrapTime < BOOTSTRAP_CACHE_TIME && projects.value.length > 0) {
      return Promise.resolve()
    }

    bootstrapPromise = (async () => {
      try {
        await Promise.all([
          loadRequirementStates(forceRefresh),
          loadRequirementOptions(forceRefresh),
          tagsStore.fetchTags().catch(err => {
            console.warn('加载系统标签失败，将使用需求中的标签:', err)
            return []
          })
        ])
        
        const projectsResponse = await getProjects({ page: 1, size: 200 })
        projects.value = extractProjects(projectsResponse)
        
        // 根据当前筛选的项目ID获取项目成员
        const projectId = filters.project_id
        if (projectId) {
          // 如果已选择项目，获取项目成员
          users.value = await loadUsersByProject(projectId)
        } else {
          // 如果没有选择项目，返回空数组（项目必先选）
          users.value = []
        }
        
        lastBootstrapTime = Date.now()
      } catch (error) {
        console.error('加载需求基础数据失败', error)
        projects.value = []
        users.value = []
      } finally {
        bootstrapPromise = null
      }
    })()

    return bootstrapPromise
  }

  // 刷新用户列表（根据当前项目）
  async function refreshUsers() {
    const projectId = filters.project_id
    if (projectId) {
      users.value = await loadUsersByProject(projectId)
    } else {
      // 如果没有选择项目，返回空数组（项目必先选）
      users.value = []
    }
  }

  // 根据项目ID加载项目成员（用于创建/编辑需求时动态加载）
  async function loadUsersForProject(projectId: string | null | undefined): Promise<User[]> {
    if (!projectId) {
      return []
    }
    return await loadUsersByProject(projectId)
  }

  // 防止重复请求的标识
  let fetchingPromise: Promise<void> | null = null

  // 从项目成员中解析用户信息
  function enrichRequirementWithUserInfo(requirement: RequirementResponse, projectMembersMap: Map<string, ProjectMember[]>): RequirementResponse {
    const projectMembers = projectMembersMap.get(requirement.project_id) || []
    
    // 解析负责人信息
    if (requirement.assignee_id && !requirement.assignee_name) {
      const assigneeMember = projectMembers.find(m => m.user_id === requirement.assignee_id)
      if (assigneeMember) {
        requirement.assignee_name = assigneeMember.name || assigneeMember.username || assigneeMember.user_name || ''
      }
    }
    
    // 解析报告人信息
    if (requirement.reporter_id && !requirement.reporter_name) {
      const reporterMember = projectMembers.find(m => m.user_id === requirement.reporter_id)
      if (reporterMember) {
        requirement.reporter_name = reporterMember.name || reporterMember.username || reporterMember.user_name || ''
      }
    }
    
    // 解析更新人信息
    if (requirement.updated_by_id && !requirement.updated_by_name) {
      const updatedByMember = projectMembers.find(m => m.user_id === requirement.updated_by_id)
      if (updatedByMember) {
        requirement.updated_by_name = updatedByMember.name || updatedByMember.username || updatedByMember.user_name || ''
      }
    }
    
    return requirement
  }

  async function fetchRequirements() {
    // 如果正在请求，返回同一个 Promise
    if (fetchingPromise) {
      return fetchingPromise
    }

    loading.value = true
    fetchingPromise = (async () => {
      try {
        const response = await getRequirements(currentQuery.value)
        if (response.success && Array.isArray(response.data)) {
          // 收集所有涉及的项目ID
          const projectIds = new Set<string>()
          response.data.forEach(req => {
            if (req.project_id) {
              projectIds.add(req.project_id)
            }
          })
          
          // 为每个项目加载项目成员
          const projectMembersMap = new Map<string, ProjectMember[]>()
          if (projectIds.size > 0) {
            await Promise.all(
              Array.from(projectIds).map(async (projectId) => {
                try {
                  const membersResponse = await getProjectMembers(projectId)
                  if (membersResponse.success && membersResponse.data) {
                    // 处理成员数据格式：后端可能返回 {members: [...], ...} 或直接返回数组
                    let members: ProjectMember[] = []
                    if (Array.isArray(membersResponse.data)) {
                      members = membersResponse.data
                    } else if (membersResponse.data && typeof membersResponse.data === 'object') {
                      // 处理 {members: [...], project_id: ..., ...} 格式
                      members = (membersResponse.data as any).members || []
                    }
                    projectMembersMap.set(projectId, members)
                  }
                } catch (error) {
                  console.warn(`加载项目 ${projectId} 的成员失败:`, error)
                  projectMembersMap.set(projectId, [])
                }
              })
            )
          }
          
          // 为每个需求填充用户信息
          requirements.value = response.data.map(req => 
            enrichRequirementWithUserInfo(req, projectMembersMap)
          )
          
          const paginationInfo = (response as any).pagination || response.pagination || paginationMeta.value
          if (paginationInfo) {
            paginationMeta.value = paginationInfo
            pagination.total = paginationInfo.total ?? pagination.total
            pagination.pages = paginationInfo.pages ?? pagination.pages
            pagination.page = paginationInfo.page ?? pagination.page
            pagination.pageSize = paginationInfo.size ?? pagination.pageSize
          } else {
            pagination.total = response.data.length
            pagination.pages = 1
          }
        } else {
          requirements.value = []
        }
      } catch (error) {
        console.error('获取需求列表失败', error)
        ElMessage.error('获取需求列表失败，请稍后重试')
        requirements.value = []
      } finally {
        loading.value = false
        fetchingPromise = null
      }
    })()

    return fetchingPromise
  }



  async function fetchRequirementDetail(id: string) {
    detailLoading.value = true
    try {
      const response = await getRequirementById(id)
      if (response.success && response.data) {
        // 如果需求有项目ID，加载项目成员并填充用户信息
        if (response.data.project_id) {
          try {
            const membersResponse = await getProjectMembers(response.data.project_id)
            if (membersResponse.success && membersResponse.data) {
              // 处理成员数据格式：后端可能返回 {members: [...], ...} 或直接返回数组
              let members: ProjectMember[] = []
              if (Array.isArray(membersResponse.data)) {
                members = membersResponse.data
              } else if (membersResponse.data && typeof membersResponse.data === 'object') {
                // 处理 {members: [...], project_id: ..., ...} 格式
                members = (membersResponse.data as any).members || []
              }
              const projectMembersMap = new Map<string, ProjectMember[]>()
              projectMembersMap.set(response.data.project_id, members)
              response.data = enrichRequirementWithUserInfo(response.data, projectMembersMap)
            }
          } catch (error) {
            console.warn('加载项目成员失败，将使用后端返回的用户信息:', error)
          }
        }
        
        activeRequirementId.value = id
        activeRequirement.value = response.data
        return response.data
      }
      ElMessage.error('获取需求详情失败')
      return null
    } catch (error) {
      console.error('获取需求详情失败', error)
      ElMessage.error('获取需求详情失败，请稍后重试')
      return null
    } finally {
      detailLoading.value = false
    }
  }

  async function setPage(page: number) {
    pagination.page = page
    await fetchRequirements()
  }

  async function setPageSize(size: number) {
    pagination.pageSize = size
    pagination.page = 1
    await fetchRequirements()
  }

  function setViewMode(mode: ViewMode) {
    viewMode.value = mode
  }

  async function applyFilters(nextFilters: Partial<RequirementFilters>) {
    const previousProjectId = filters.project_id
    Object.assign(filters, nextFilters)
    pagination.page = 1
    
    // 如果项目ID发生变化，刷新用户列表（项目成员）
    if (nextFilters.project_id !== undefined && nextFilters.project_id !== previousProjectId) {
      await refreshUsers()
    }
    
    await fetchRequirements()
  }

  async function resetFilters() {
    // 保留项目ID，不重置（项目是必选的）
    const currentProjectId = filters.project_id
    Object.assign(filters, {
      search: '',
      // project_id 保留，不重置
      status: undefined,
      priority: undefined,
      requirement_type: undefined,
      source: undefined,
      assignee_id: undefined,
      reporter_id: undefined,
      has_version: undefined,
      created_start: undefined,
      created_end: undefined,
      sort_by: undefined,
      sort_order: undefined
    })
    // 恢复项目ID
    if (currentProjectId) {
      filters.project_id = currentProjectId
    }
    pagination.page = 1
    await fetchRequirements()
  }

  async function setSort(sortBy?: string, sortOrder?: 'asc' | 'desc') {
    filters.sort_by = sortBy
    filters.sort_order = sortOrder
    pagination.page = 1 // 排序时重置到第一页
    await fetchRequirements()
  }

  function toggleSelection(ids: string[], currentPageIds?: string[]) {
    // 如果提供了当前页面的ID列表，进行智能合并
    if (currentPageIds && currentPageIds.length > 0) {
      // 获取当前页面的需求ID集合
      const currentPageIdSet = new Set(currentPageIds)
      // 移除当前页面之前的选择（保留其他页面的选择）
      selectedIds.value = selectedIds.value.filter(id => !currentPageIdSet.has(id))
      // 添加当前页面新选择的需求
      selectedIds.value = [...selectedIds.value, ...ids]
    } else {
      // 如果没有提供当前页面ID列表，直接替换（兼容旧逻辑）
      selectedIds.value = ids
    }
  }

  function clearSelection() {
    selectedIds.value = []
  }

  function openCreateDrawer(defaultProjectId?: string | null) {
    // 打开创建面板
    detailVisible.value = true
    editorDefaultProjectId.value = defaultProjectId ?? null
    // 清空当前需求数据
    activeRequirementId.value = null
    activeRequirement.value = null
  }

  async function openEditDrawer(requirementId: string) {
    // 如果已经打开了同一个需求，直接返回
    if (activeRequirementId.value === requirementId && detailVisible.value) {
      return
    }
    // 打开详情面板并切换到编辑模式
    detailVisible.value = true
    editorMode.value = 'edit'
    editorDefaultProjectId.value = null
    // 获取需求详情
    if (!activeRequirement.value || activeRequirement.value.id !== requirementId) {
      await fetchRequirementDetail(requirementId)
    }
  }

  async function submitRequirement(payload: RequirementCreate | RequirementUpdate, id?: string) {
    detailLoading.value = true
    try {
      if (id && editorMode.value === 'edit') {
        const response = await updateRequirement(id, payload as RequirementUpdate)
        if (response.success && response.data) {
          ElMessage.success('需求更新成功')
          await fetchRequirements()
          await fetchRequirementDetail(id)
          // 更新成功后切换回查看模式
          editorMode.value = 'view'
          return response.data
        }
        ElMessage.error(response.message || '需求更新失败')
      } else {
        const response = await createRequirement(payload as RequirementCreate)
        if (response.success && response.data) {
          ElMessage.success('需求创建成功')
          await fetchRequirements()
          // 创建成功后关闭面板
          detailVisible.value = false
          return response.data
        }
        ElMessage.error(response.message || '需求创建失败')
      }
      return null
    } catch (error) {
      console.error('提交需求失败', error)
      ElMessage.error('提交需求失败，请稍后重试')
      return null
    } finally {
      detailLoading.value = false
    }
  }

  async function openDetailPanel(id: string) {
    // 如果已经打开了同一个需求，直接返回
    if (activeRequirementId.value === id && detailVisible.value) {
      return
    }
    // 先设置 activeRequirementId，这样 index.vue 中的条件判断就能正确工作
    activeRequirementId.value = id
    editorMode.value = 'view'
    // 如果已经有缓存的需求数据且 ID 匹配，直接显示，否则先加载数据
    if (activeRequirement.value && activeRequirement.value.id === id) {
      detailVisible.value = true
    } else {
      // 先加载数据，加载完成后再显示
      await fetchRequirementDetail(id)
      detailVisible.value = true
    }
  }

  function closeDetailPanel() {
    detailVisible.value = false
    activeRequirementId.value = null
    activeRequirement.value = null
    editorDefaultProjectId.value = null
  }

  async function updateRequirementStatus(id: string, status: string) {
    const requirement = requirements.value.find(item => item.id === id)
    if (!requirement) {
      console.warn(`需求 ${id} 不存在于当前列表中`)
      return false
    }
    
    const previousStatus = requirement.status
    if (previousStatus === status) {
      // 状态相同，无需更新
      return true
    }

    // 先更新本地状态，实现乐观更新
    // 这样可以立即更新UI，提升用户体验
    requirement.status = status as RequirementStatus
    
    try {
      const result = await apiUpdateRequirementStatus(id, { status: status as RequirementStatus })
      
      // 检查API响应是否成功
      if (!result.success || !result.data) {
        // API调用失败，回滚状态
        requirement.status = previousStatus
        console.error('更新需求状态失败: API返回失败', result)
        return false
      }
      
      // 使用API返回的数据完全更新需求对象，确保所有字段都得到更新
      const index = requirements.value.findIndex(item => item.id === id)
      if (index !== -1) {
        // 保持需求在数组中的位置，只更新数据
        requirements.value[index] = { ...requirements.value[index], ...result.data }
      }
      
      // 如果当前有活动需求，也更新它
      if (activeRequirement.value && activeRequirement.value.id === id) {
        activeRequirement.value = { ...activeRequirement.value, ...result.data }
      }
      
      // 不显示成功消息，由调用方决定是否显示
      return true
    } catch (error) {
      // 回滚状态
      requirement.status = previousStatus
      console.error('更新需求状态失败', error)
      // 不显示错误消息，由调用方决定是否显示
      return false
    }
  }

  return {
    requirements,
    loading,
    pagination,
    viewMode,
    filters,
    selectedIds,
    activeRequirementId,
    activeRequirement,
    editorVisible,
    editorMode,
    editorLoading,
    editorDefaultProjectId,
    detailVisible,
    detailLoading,
    tagOptions,
    projects,
    users,
    statusOptions,
    allStatusOptions,
    priorityOptions,
    typeOptions,
    sourceOptions,
    hasSelection,
    currentQuery,
    bootstrapOptions,
    refreshUsers,
    loadUsersForProject,
    fetchRequirements,
    fetchRequirementDetail,
    setPage,
    setPageSize,
    setSort,
    setViewMode,
    applyFilters,
    resetFilters,
    toggleSelection,
    clearSelection,
    openCreateDrawer,
    openEditDrawer,
    submitRequirement,
    openDetailPanel,
    closeDetailPanel,
    updateRequirementStatus
  }
})


